package us.wili.dev.client.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import us.wili.dev.client.jwt.JwtSessionUtil;
import us.wili.dev.client.jwt.JwtUser;
import us.wili.dev.client.jwt.JwtUtil;
import us.wili.dev.client.model.req.LoginReq;
import us.wili.dev.client.model.rsp.LoginRsp;
import us.wili.dev.client.model.rsp.UserLoginRsp;
import us.wili.dev.client.service.ClientLoginService;
import us.wili.dev.client.service.ClientUserService;
import us.wili.dev.common.exception.BaseExceptionEnum;
import us.wili.dev.exception.ErrorCode;
import us.wili.dev.exception.UserException;
import us.wili.dev.model.entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Service
public class ClientLoginServiceImpl implements ClientLoginService {
    @Autowired
    private JwtSessionUtil jwtSessionUtil;

    private Function<String,String> generateErrorCountKey = username -> "user.login.invalid.pwd."+ username;

    @Autowired
    @Qualifier("jdkRedisTemplate")
    private RedisTemplate<String, Integer> redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public LoginRsp getuser(User user,String token) {
        LoginRsp rsp =new LoginRsp();
        rsp.setUserid(user.getId());
        rsp.setToken(token);
        return rsp;
    }

    /**
     * 核对密码是否一致
     * @param pwd 数据库中储藏的用户密码
     * @param normalPwd 用户未加密的密码
     * @param salt 盐
     * @return 核对结果
     */
    private boolean checkPwd(String pwd, String normalPwd, String salt) {
        return jwtUtil.checkPwd(pwd, normalPwd, salt);
    }

    /**
     * 检查用户登录密码错误的次数是否超过上限并返回错误次数,如果超过上限不给登录
     * @param phone 登录手机号码
     * @return 错误次数
     */
    private int checkPwdErrorCount(String phone) {
        /*String key = generateErrorCountKey.apply(phone);
        int errorCount = Optional.ofNullable(redisTemplate.opsForValue().get(key)).orElse(0);
        if (errorCount >= SystemConst.MAX_PWD_ERROR_TIME) {
            throw new UserException(ErrorCode.USER_PWD_TIME_EXCEED_MAX_TIME);
        }
        return errorCount;*/
        return 0;
    }

    /**
     * 将用户转jwtUser,设置需要传递的用户信息
     * @param user 需要转换为jwtUser的user实例
     * @return 生成的jwtUser
     */
    private JwtUser generateJwtUser(User user) {
        JwtUser jwtUser = new JwtUser();
        jwtUser.setAnonymous(false);
        jwtUser.setUserId(user.getId());
        jwtUser.setNickname(user.getName());
        return jwtUser;
    }

}
